package com.training.api.controller;

import com.training.api.service.UserService;
import com.training.bean.User;
import com.training.bean.dao.UserDTO;
import com.training.jwt.JWTUtils;
import com.training.base.Result;
import com.training.utils.UrlUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param phone 手机号
     * @param password 密码
     * @param request HTTP请求对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseEntity<Result<UserDTO>> login(@RequestParam String phone, @RequestParam String password, HttpServletRequest request) {
        try {
            User user = userService.findUser(phone);
            if (user != null && user.phone.equals(phone) && user.password.equals(password)){
                // 检查用户是否被禁用
                if (user.getDisabled()) {
                    return ResponseEntity.status(401).body(Result.fail(401, "用户已被禁用"));
                }
                
                // 获取用户ID和用户名，并将其放入payload
                Map<String, String> payload = new HashMap<>();
                payload.put("id", String.valueOf(user.id));
                payload.put("phone", user.phone);
                payload.put("nickname", user.nickname);
                payload.put("userType", "user"); // 添加用户类型标识

                // 生成JWT的令牌
                String token = JWTUtils.getToken(payload);
                user.setAvatar(UrlUtils.buildFullUrl(request, user.getAvatar()));
                return ResponseEntity.ok(new Result<>(200, "登录成功", new UserDTO(token, user)));
            }else {
                return ResponseEntity.status(500).body(Result.fail(500, "登录失败: 账号或密码错误"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Result.fail(500, "登录失败: " + e.getMessage()));
        }
    }
}